// Copyright (c) 2023 CHANGLEI. All rights reserved.

import 'package:flutter/rendering.dart';
import 'package:tverify/src/ui_decorator.dart';

/// Created by changlei on 2023/8/15.
///
/// 扩展
abstract interface class Codable {
  /// toMap
  Map<String, dynamic> toMap();
}

/// size
extension SizeToMap on Size {
  /// toMap
  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'width': width,
      'height': height,
    };
  }
}

/// Rect
extension RectToMap on Rect {
  /// toMap
  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'x': left,
      'y': top,
      'width': width,
      'height': height,
    };
  }
}

/// Color
extension ColorToMap on Color {
  /// toMap
  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'red': red / 0xFF,
      'green': green / 0xFF,
      'blue': blue / 0xFF,
      'alpha': alpha / 0xFF,
      'value': value,
    };
  }
}

/// EdgeInsets
extension EdgeInsetsToMap on EdgeInsets {
  /// toMap
  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'left': left,
      'top': top,
      'right': right,
      'bottom': bottom,
    };
  }
}

/// NSAttributedStringKey
extension AttributesToMap on Map<NSAttributedStringKey, dynamic> {
  /// toMap
  Map<String, dynamic> toMap() {
    return map((key, value) => MapEntry(key.rawValue, _encode(value)));
  }

  dynamic _encode(dynamic value) {
    return switch (value) {
      Size() => value.toMap(),
      Rect() => value.toMap(),
      Color() => value.toMap(),
      EdgeInsets() => value.toMap(),
      Map<NSAttributedStringKey, dynamic>() => value.toMap(),
      Codable() => value.toMap(),
      num() => value,
      bool() => value,
      String() => value,
      List<dynamic>() => value.map(_encode).toList(),
      Map<dynamic, dynamic>() => value.map((key, value) => MapEntry(key, _encode(value))),
      _ => value,
    };
  }
}
